import axios from "axios";
import { message } from "ant-design-vue";
import Cookies from "js-cookie";
import router from "@/router";

const config = {
  baseURL: import.meta.env.VITE_APP_BASE_API,
  headers: { "content-type": "application/json" },
  timeout: 60000,
};
const api = axios.create(config);
api.interceptors.request.use((con) => {
  let token = Cookies.get("token");
  con.headers = con.headers || {};
  if (token) {
    con.headers.Auth = `Bearer ${ token }`
  }
  const uid = Cookies.get('uid') 
  if (uid) {
    con.url = con.url.indexOf('?') >= 0 ? `${con.url}&uid=${uid}` : `${con.url}?uid=${uid}`
  }
  if (con.data instanceof FormData) {
    Object.assign(con.headers, { "content-type": "multipart/form-data" });
  }
  return con;
});
api.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code == '2015' || res.code == '10007') {
      return router.push({ path: "/login" });
    }
    if (res.code !== '200') {
      message.error(res.message);
      return Promise.reject(res);
    }
    return res;
  },
  () => {
    message.error("网络异常");
    return Promise.reject("网络异常");
  }
);
export default api;
